package com.spring.demo.security;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import com.spring.demo.model.user.User;
import com.spring.demo.service.user.UserService;

/**
 * 获取用户信息，并设置对应的角色
 * @author ld2016
 *
 */
//@Component("customUserDetailService")
@Service("customUserDetailService")
public class CustomUserDetailService implements UserDetailsService {

	@Resource(name = UserService.SERVICE_NAME)
	private UserService userService;
	
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// TODO Auto-generated method stub
		List<User> list = userService.selectUser(username, null);
		if(list!=null&&list.size()>0) {
			//设置角色
			/*
			 * 设置角色的时候前面加上ROLE_
			 */
			Collection<GrantedAuthority> auths = new ArrayList<>();
			User user = list.get(0);
			if(list.get(0).getType()==1) {
				auths.add(new SimpleGrantedAuthority("ROLE_ADMIN"));
			}else {
				auths.add(new SimpleGrantedAuthority("ROLE_USER"));
			}
			return new org.springframework.security.core.userdetails.User(user.getUserName(),user.getPassWord(),auths);
		}
		throw new UsernameNotFoundException("User '" + username
				+ "' not found.");
	}

}
